<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import SongItem from '@/components/SongItem.vue'
import { usePlayerStore, useMusicStore, useUserProfileStore } from '@/store'
import { useRouter } from 'vue-router'

// 导入轮播图图片
import banner1 from '@/assets/banner1.jpg'
import banner2 from '@/assets/banner2.jpg'
import banner3 from '@/assets/banner3.jpg'
import banner4 from '@/assets/banner4.jpg'

// 轮播图数据
const slides = [
  { 
    id: 1, 
    image: banner1, 
  },
  { 
    id: 2, 
    image: banner2, 
  },
  { 
    id: 3, 
    image: banner3, 
  },
  { 
    id: 4, 
    image: banner4, 
  }
]

const currentSlide = ref(0)
let slideInterval = null

// 切换到下一张幻灯片
const nextSlide = () => {
  currentSlide.value = (currentSlide.value + 1) % slides.length;
}

// 切换到上一张幻灯片
const prevSlide = () => {
  currentSlide.value = (currentSlide.value - 1 + slides.length) % slides.length;
}

// 切换到指定幻灯片
const goToSlide = (index) => {
  currentSlide.value = index
}

// 启动自动轮播
const startSlideShow = () => {
  stopSlideShow(); // 确保没有多个计时器运行
  slideInterval = setInterval(() => {
    nextSlide()
  }, 5000) // 5秒切换一次
}

// 停止自动轮播
const stopSlideShow = () => {
  if (slideInterval) {
    clearInterval(slideInterval)
  }
}

// 添加到setup中
const playerStore = usePlayerStore()
const musicStore = useMusicStore()
const router = useRouter()

// 最新音乐数据
const latestSongs = computed(() => musicStore.allMusic)

// 获取最新音乐列表
const fetchLatestSongs = async () => {
  const songs = await musicStore.fetchAllMusic()
  if (songs.length > 0) {
    // 将整个列表添加到播放器
    playerStore.setPlaylist(songs)
    
    // 检查是否有当前播放歌曲ID，如果有则高亮显示
    if (playerStore.currentSong.id) {
      // 可以在此处添加高亮逻辑
    }
  }
}

// 处理播放/暂停
const handlePlay = ({ id, playing }) => {
  if (playing) {
    // 找到要播放的歌曲
    const songToPlay = latestSongs.value.find(song => song.id === id)
    if (songToPlay) {
      // 更新到播放器状态
      playerStore.playSong({
        songId: songToPlay.id,
        songName: songToPlay.title,
        artist: songToPlay.artist,
        coverUrl: songToPlay.coverUrl,
        musicUrl: songToPlay.musicUrl,
        album: songToPlay.album,
        isLiked: songToPlay.isFavorite === 1
      })
    }
  } else {
    // 暂停当前播放的歌曲
    playerStore.togglePlay()
  }
}

// 检查用户是否已登录
const isLoggedIn = computed(() => {
  return localStorage.getItem('token') !== null
})

onMounted(() => {
  fetchLatestSongs()
  startSlideShow()
})

onBeforeUnmount(() => {
  stopSlideShow()
})

const userProfileStore = useUserProfileStore()
// 当用户信息突然没有时，重新登录
watch(userProfileStore.userInfo, () => {
  if (userProfileStore.userInfo === null) {
    ElMessage.error('用户信息获取失败，请重新登录')
    router.push('/login')
  }
})

// 添加组件名称，用于 keep-alive
defineOptions({
  name: 'Home'
})
</script>

<template>
  <div class="home">
    <!-- 轮播图区域 -->
    <div class="banner-section">
      <div class="banner">
        <div class="banner-bg" :style="{ backgroundImage: `url(${slides[currentSlide].image})` }"></div>
        <div class="banner-content">
          <transition-group name="fade">
            <div v-for="(slide, index) in slides" :key="slide.id" 
                v-show="currentSlide === index" 
                class="slide">
              <img :src="slide.image">
            </div>
          </transition-group>
        </div>
        
        <!-- 指示器 -->
        <div class="indicator">
          <span v-for="(slide, index) in slides" 
                :key="slide.id" 
                class="dot" 
                :class="{ active: currentSlide === index }"
                @click="goToSlide(index)">
          </span>
        </div>
      </div>
      
      <!-- 左右箭头 (移到外部) -->
      <div class="arrow left" @click="prevSlide">&lt;</div>
      <div class="arrow right" @click="nextSlide">&gt;</div>
    </div>

    <!-- 内容区域 -->
    <div class="section">
      <!-- 最新音乐 -->
      <div class="section-header">
        <h2>最新音乐</h2>
        <a href="#" class="more">更多 &gt;</a>
      </div>
      
      <!-- 添加空状态显示 -->
      <div v-if="latestSongs.length === 0" class="empty-state">
        <div class="empty-icon">
          <i class="el-icon-music"></i>
        </div>
        <p class="empty-text">暂无最新音乐</p>
        <p class="empty-subtext">音乐正在路上，请稍后再来~</p>
        <el-button style="width: 100px;" type="primary" class="netease-red-btn" @click="$router.push('/upload')" v-if="isLoggedIn">
          上传我的音乐
        </el-button>
      </div>
      
      <!-- 有数据时显示歌曲列表 -->
      <div v-else class="latest-songs">
        <SongItem 
          v-for="(song, index) in latestSongs" 
          :key="song.id"
          :rank="index + 1"
          :songName="song.title"
          :artist="song.artist"
          :isLiked="song.isFavorite === 1"
          :songId="song.id"
          :album="song.album"
          :duration="song.duration"
          :coverUrl="song.coverUrl"
          :musicUrl="song.musicUrl"
          @play="handlePlay"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.home {
  width: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden; /* 防止水平滚动条 */
}

/* 轮播图区域背景 */
.banner-section {
  width: 100vw; /* 使用视口宽度而不是百分比 */
  position: relative;
  margin-top: -1px;
  margin-left: calc(-50vw + 50%); /* 这个技巧使元素在任何容器中都能占满整个视口宽度 */
  overflow: hidden;
  background-color: #232323;
}

/* 轮播图样式 */
.banner {
  position: relative;
  height: 300px;
  width: 100%;
  margin: 0 auto;
  overflow: visible;
}

/* 模糊背景 */
.banner-bg {
  position: absolute;
  top: 0;
  left: -50px; /* 扩展边缘，确保模糊效果覆盖整个区域 */
  right: -50px;
  bottom: 0;
  background-size: cover;
  background-position: center;
  filter: blur(20px);
  opacity: 0.8;
  transform: scale(1.2); /* 增加放大比例以确保完全覆盖 */
}

.banner-content {
  position: relative;
  width: 1000px;
  height: 100%;
  margin: 0 auto;
  overflow: hidden;
  z-index: 1;
}

.slide {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.slide-info {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  text-align: center;
  width: 80%;
  max-width: 600px;
  z-index: 2;
}

.slide-title {
  font-size: 22px;
  margin: 0 0 10px 0;
  font-weight: normal;
}

.slide-desc {
  font-size: 32px;
  margin: 0 0 20px 0;
  font-weight: bold;
  letter-spacing: 2px;
}

.slide-line {
  width: 50px;
  height: 3px;
  background-color: #e5c787;
  margin: 0 auto;
}

.arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  font-size: 36px;
  cursor: pointer;
  z-index: 10;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.arrow:hover {
  opacity: 1;
}

.arrow.left {
  left: 5%;
}

.arrow.right {
  right: 5%;
}

.indicator {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  z-index: 10;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 0 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.dot.active {
  background-color: #fff;
}

/* 轮播图过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 通用版块样式 */
.section {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 20px;
  padding-bottom: 90px; /* 增加底部内边距，防止内容被播放器遮挡 */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h2 {
  font-size: 20px;
  margin: 0;
}

.more {
  color: #666;
  font-size: 12px;
  text-decoration: none;
}

.more:hover {
  color: #c20c0c;
  text-decoration: underline;
}

.latest-songs {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 10px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: #d9d9d9;
}

.empty-icon i {
  display: inline-block;
  width: 60px;
  height: 60px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23d9d9d9"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6zm-2 16c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/></svg>');
  background-repeat: no-repeat;
  background-position: center;
}

.empty-text {
  font-size: 18px;
  color: #666;
  margin: 5px 0;
}

.empty-subtext {
  font-size: 14px;
  color: #999;
  margin: 0 0 20px 0;
}

.netease-red-btn {
  background-color: #c20c0c;
  border-color: #c20c0c;
  color: #fff;
}

.netease-red-btn:hover {
  background-color: #d33a3a;
  border-color: #d33a3a;
}
</style> 